package com.example.sunmiv1.adapter;

import android.annotation.SuppressLint;
import android.content.Context;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.callback.RVCallback;
import com.example.sunmiv1.entity.AllocationGoodsInfo;
import com.example.sunmiv1.entity.AllocationGoodsInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;

import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.ContentValues.TAG;

public class AllocationGoodsAdapter extends RecyclerView.Adapter<AllocationGoodsAdapter.prcgVholder>{
    private List<AllocationGoodsInfo.DataBean> list;
    private String pricePermission;// 門店查看價格權限
    private Context context;
    private CheckBoxListener mCheckBoxListener;

    public AllocationGoodsAdapter(Context context, List<AllocationGoodsInfo.DataBean> list) {
        this.context = context;
        this.list = list;
        ACache aCache = ACache.get(context);
        pricePermission=aCache.getAsString("showPrice");
    }


    @Override
    public AllocationGoodsAdapter.prcgVholder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.deposit_goods_adapter, parent, false);
        return new AllocationGoodsAdapter.prcgVholder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(AllocationGoodsAdapter.prcgVholder viewHolder, int position) {
        viewHolder.depositGoodsCheck.setOnCheckedChangeListener(null);
        viewHolder.depositGoodsCheck.setChecked(list.get(position).isChecked());
        viewHolder.depositGoodsCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mCheckBoxListener.setCheckBoxListener(isChecked, position);
        });
        viewHolder.depositGoodsName.setText(list.get(position).getGoods_name());
        viewHolder.depositGoodsFreightNumber.setText(list.get(position).getGoods_number());
        viewHolder.depositGoodsCode.setText(list.get(position).getGoods_code());
        viewHolder.depositGoodsStock.setText(list.get(position).getGoods_num() + "");
        viewHolder.depositGoodsPrice.setText(list.get(position).getStock_price() + "");
        if(TextUtils.isEmpty(list.get(position).getCompany())){
            ((View)viewHolder.infoUnit.getParent()).setVisibility(View.GONE);
        }else {
            ((View) viewHolder.infoUnit.getParent()).setVisibility(View.VISIBLE);
            viewHolder.infoUnit.setText(list.get(position).getCompany());
        }
//        viewHolder.infoCostPrice.setText(String.valueOf(list.get(position).getCost_price()));
        viewHolder.layoutCostPrice.setVisibility(View.GONE);
        Tools.hideViewInItem(list.get(position).getSku_name(),viewHolder.infoSkuName);
        if ("2".equals(list.get(position).getPricing_method())) {//稱重商品
            viewHolder.depositGoodsNum.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        } else {
            viewHolder.depositGoodsNum.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
        }

        viewHolder.depositGoodsPrice.setText(list.get(position).getStock_price()+"");
        final TextWatcher dgpTextWatcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                limitDecimal(charSequence,viewHolder.depositGoodsPrice);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(viewHolder.depositGoodsPrice.hasFocus()){
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        list.get(position).setStock_price(Double.parseDouble(s.toString().trim()));
                    } else {
                        list.get(position).setStock_price(0);
                    }
                }

            }
        };
        setETFocusChangeListener(position, dgpTextWatcher, viewHolder.depositGoodsPrice);

        viewHolder.depositGoodsNum.setText(list.get(position).getOutput_num());
        LogUtil.i("getOutput_num():"+list.get(position).getOutput_num());
        final TextWatcher dgnTextWatcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
//                limitDecimal(charSequence,viewHolder.depositGoodsNum);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(viewHolder.depositGoodsNum.hasFocus()){
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        list.get(position).setOutput_num(s.toString().trim());
                        LogUtil.i("setOutput_num()1:"+s.toString().trim());
                    } else {
                        list.get(position).setOutput_num("");
                        LogUtil.i("setOutput_num()2:"+s.toString().trim());
                    }

                }
            }
        };
        setETFocusChangeListener(position, dgnTextWatcher, viewHolder.depositGoodsNum);


        viewHolder.depositGoodsRemark.setText(list.get(position).getRemark());
        final TextWatcher dgrTextWatcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(viewHolder.depositGoodsRemark.hasFocus()) {
                    list.get(position).setRemark(s.toString());
                }
            }
        };
        setETFocusChangeListener(position, dgrTextWatcher, viewHolder.depositGoodsRemark);

        if("2".equals(pricePermission)){
//            viewHolder.layoutCostPrice.setVisibility(View.GONE);
            ((View)viewHolder.depositGoodsPrice.getParent()).setVisibility(View.GONE);
        }
        if ("1".equals(list.get(position).getSerial_number_state())) {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            viewHolder.depositGoodsNum.setVisibility(View.GONE);
            Log.e(TAG, "onBindViewHolder: 商品的庫存========"+list.get(position).getOutput_num() );
            if (TextUtils.isEmpty(list.get(position).getOutput_num())) {
                viewHolder.inventorySearchAdapterInventoryTv.setText("0");
            }else{
                viewHolder.inventorySearchAdapterInventoryTv.setText(list.get(position).getOutput_num());
            }
        } else {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            viewHolder.depositGoodsNum.setVisibility(View.VISIBLE);
        }
        final int index = position;
        viewHolder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(index);
            }
        });
    }

    private Choose choose;
    public void setChoose(Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index);
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    static class prcgVholder extends RecyclerView.ViewHolder {
        @BindView(R.id.depositGoods_check)
        CheckBox depositGoodsCheck;
        @BindView(R.id.depositGoods_name)
        TextView depositGoodsName;
        @BindView(R.id.info_sku_name)
        TextView infoSkuName;
        @BindView(R.id.layout_sku_name)
        RelativeLayout layoutSkuName;
        @BindView(R.id.depositGoods_freightNumber)
        TextView depositGoodsFreightNumber;
        @BindView(R.id.depositGoods_code)
        TextView depositGoodsCode;
        @BindView(R.id.depositGoods_tvStock)
        TextView depositGoodsTvStock;
        @BindView(R.id.depositGoods_stock)
        TextView depositGoodsStock;
        @BindView(R.id.info_cost_price)
        TextView infoCostPrice;
        @BindView(R.id.layout_cost_price)
        RelativeLayout layoutCostPrice;
        @BindView(R.id.info_unit)
        TextView infoUnit;
        @BindView(R.id.layout_unit)
        RelativeLayout layoutUnit;
        @BindView(R.id.depositGoods_tvPrice)
        TextView depositGoodsTvPrice;
        @BindView(R.id.depositGoods_price)
        EditText depositGoodsPrice;
        @BindView(R.id.depositGoods_tvNum)
        TextView depositGoodsTvNum;
        @BindView(R.id.depositGoods_num)
        EditText depositGoodsNum;
        @BindView(R.id.depositGoods_remark)
        EditText depositGoodsRemark;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;


        private prcgVholder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     *  限制小數點後三位
     * @param charSequence   str
     * @param et   et
     */
    private void limitDecimal(CharSequence charSequence, EditText et) {
        LogUtil.i("onTextChanged: charSequence=" + charSequence.toString());
        if (charSequence.toString().contains(".")) {
            if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                et.setText(charSequence.toString().
                        substring(0, charSequence.toString().length() - 1));
                et.setSelection(charSequence.length() - 1);
            } else {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                    charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                    et.setText(charSequence);
                    et.setSelection(charSequence.length());
                }
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            et.setText(charSequence);
            et.setSelection(2);
        }

        if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                et.setText(charSequence.subSequence(1, 2));
                et.setSelection(1);
            }
        }
    }

    /**
     * 設置edittext焦點的監聽器
     * @param position      pos
     * @param textWatcher   watcher
     * @param editText      et
     */
    private void setETFocusChangeListener(int position, TextWatcher textWatcher, EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                ((EditText) v).addTextChangedListener(textWatcher);
                Log.e("addTextChanged", position + "");
            } else {
                ((EditText) v).removeTextChangedListener(textWatcher);
                Log.e("removeTextChanged", position + "");
            }
        });
    }
    /**
     * 給editText，添加監聽並防止數據渲染混亂
     *
     * @param beansParam   java bean中的字段
     * @param et            editText
     */
    private void setEditText( Class clazz,String beansParam,EditText et){
        et.setText(beansParam);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                mList.get(position).setRemarks(s.toString());
            }
        });
    }

    // 全選
    public void checkAll() {
        for (AllocationGoodsInfo.DataBean dataBean : list) {
            dataBean.setChecked(true);
        }
        notifyDataSetChanged();
    }

    // 全不選
    public void checkAllNot() {
        for (AllocationGoodsInfo.DataBean dataBean : list) {
            dataBean.setChecked(false);
        }
        notifyDataSetChanged();
    }

    // 移除一個
    public void removeOne(int position) {
        list.remove(position);
    }

    /* 移除多個 */
    public void removeMore(SparseArray<Integer> positions) {
//        list.r
    }
    public static interface CheckBoxListener {
        void setCheckBoxListener(boolean isChecked, int position);
    }

    public void setCBListener(AllocationGoodsAdapter.CheckBoxListener cbListener) {
        this.mCheckBoxListener = cbListener;
    }


    private void setInfo(){

    }

}
